package com.mo.demo.guava;

import com.google.common.cache.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutionException;

@Slf4j
public class GuavaLoadingCacheTest {
    public static void main(String[] args) throws ExecutionException {
        CacheLoader<String, String> loader = new CacheLoader<String, String> () {
            public String load(String key) throws Exception {
                Thread.sleep(1000); //休眠1s，模拟加载数据
                log.info(key + " 加载自 cacheLoader");
                return key + key + key;
            }
        };


        LoadingCache<String, String> loadingCache = CacheBuilder.newBuilder()
                .build(loader);


        for (int i = 0; i < 3; i++) {
            int finalI = i;
            new Thread(new Runnable() {
                @SneakyThrows
                @Override
                public void run() {
                    log.info("key={}, value={}",(finalI +1),loadingCache.get((finalI +1)+""));
                }
            }).start();
            new Thread(new Runnable() {
                @SneakyThrows
                @Override
                public void run() {
                    log.info("key={}, value={}",(finalI +1),loadingCache.get((finalI +1)+""));
                }
            }).start();

        }

        // 输出
        // 05:21:43.102 [Thread-3] INFO com.mo.demo.guava.GuavaLoadingCacheTest - 2 加载自 cacheLoader
        // 05:21:43.102 [Thread-1] INFO com.mo.demo.guava.GuavaLoadingCacheTest - 1 加载自 cacheLoader
        // 05:21:43.102 [Thread-5] INFO com.mo.demo.guava.GuavaLoadingCacheTest - 3 加载自 cacheLoader
        // 05:21:43.117 [Thread-2] INFO com.mo.demo.guava.GuavaLoadingCacheTest - key=2, value=222
        // 05:21:43.117 [Thread-0] INFO com.mo.demo.guava.GuavaLoadingCacheTest - key=1, value=111
        // 05:21:43.117 [Thread-5] INFO com.mo.demo.guava.GuavaLoadingCacheTest - key=3, value=333
        // 05:21:43.117 [Thread-3] INFO com.mo.demo.guava.GuavaLoadingCacheTest - key=2, value=222
        // 05:21:43.117 [Thread-4] INFO com.mo.demo.guava.GuavaLoadingCacheTest - key=3, value=333
        // 05:21:43.117 [Thread-1] INFO com.mo.demo.guava.GuavaLoadingCacheTest - key=1, value=111

    }
}
